package com.cckj.common.service;

import com.cckj.common.constants.EasyBootConstants;
import com.cckj.common.exception.BusinessException;
import com.cckj.common.utils.RedisUtils;
import com.cckj.common.base.LoginUserEntity;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Data
@Configuration
@ConfigurationProperties(prefix = "jwt")
public class JwtTokenService {

    private String secret;
    private Integer expireTime;
    private String header;
    private String prefix;

    @Autowired
    RedisUtils redisUtils;

    // 一分钟秒数
    private final long MILLIS_MINUTE = 60 * 1000L;

    // 1小时秒数 自动刷新token
    private final long MILLIS_HOUR = 60 * MILLIS_MINUTE;

    // 一天秒数
    private final long MILLIS_DATE = 24 * MILLIS_HOUR;

    /**
     * 创建令牌
     *
     * @param loginUser 用户信息
     * @return 令牌 string
     * @author chengni
     * @date 2020/08/26 16:36
     */
    public String createToken(LoginUserEntity loginUser) {
        String token = UUID.randomUUID().toString().trim().replace("-","");

        loginUser.setToken(token);
        refreshToken(loginUser);

        Map<String, Object> claims = new HashMap<>(1);
        claims.put(EasyBootConstants.LOGIN_USER_KEY, token);
        return prefix + Jwts.builder()
                // 放入用户ID
                .setId(loginUser.getId())
                // 主题用户名
                .setSubject(loginUser.getName())
                // 签发时间
                .setIssuedAt(new Date())
                // 签发者
                .setIssuer("easyBoot")
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
    }

    /**
     * tokenId
     *
     * @param uuid uuid
     * @return tokenId
     * @author chengni
     * @date 2020/9/10 20:13
     */
    private String getTokenKey(String uuid) {
        return EasyBootConstants.LOGIN_TOKEN_KEY + uuid;
    }
    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     * @author chengni
     * @date 2020/08/26 16:35
     */
    public void refreshToken(LoginUserEntity loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_DATE);

        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        redisUtils.set(userKey, loginUser, expireTime, TimeUnit.DAYS);
    }


    /**
     * 获取请求token
     *
     * @param request HttpServletRequest
     * @return token
     * @author chengni
     * @date 2020/08/26 16:36
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(prefix)) {
            return token.replace(prefix, "");
        }else{
            return null;
        }
    }


    /**
     * 验证令牌有效期，相差不足1小时，自动刷新缓存
     *
     * @param loginUser the login user
     * @author chengni
     * @date 2020/08/26 16:35
     */
    public void verifyToken(LoginUserEntity loginUser) {
        long expire = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        long diffTime = expire - currentTime;
        if (diffTime <= 0){
            throw new BusinessException("token失效");
        }
        if (diffTime <= MILLIS_HOUR) {
            // 刷新令牌有效期
            refreshToken(loginUser);
        }
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     * @author chengni
     * @date 2020/08/26 16:36
     */
    private Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 获取用户身份信息
     *
     * @param request the request
     * @return 用户信息 login user
     * @author chengni
     * @date 2020/08/26 16:36
     */
    public LoginUserEntity getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            Claims claims = parseToken(token);
            // 解析对应的权限以及用户信息
            String uuid = (String) claims.get(EasyBootConstants.LOGIN_USER_KEY);
            return redisUtils.get(getTokenKey(uuid));
        }
        return null;
    }


    /**
     * 设置用户身份信息
     *
     * @param loginUser the login user
     * @author chengni
     * @date 2020/08/26 16:36
     */
    public void setLoginUser(LoginUserEntity loginUser) {
        if (null != loginUser && StringUtils.isNotEmpty(loginUser.getToken())) {
            refreshToken(loginUser);
        }
    }

    /**
     * 删除用户身份信息
     *
     * @param token the token
     * @author chengni
     * @date 2020/08/26 16:36
     */
    public void delLoginUser(String token) {
        if (StringUtils.isNotEmpty(token)) {
            String userKey = getTokenKey(token);
            redisUtils.delete(userKey);
        }
    }

}
